package com.sanri.tools.modules.mock.l7.websocket.chat.service;

import com.sanri.tools.modules.core.dtos.param.PageParam;
import com.sanri.tools.modules.core.exception.ToolException;
import com.sanri.tools.modules.core.security.UserOpenService;
import com.sanri.tools.modules.core.security.UserService;
import com.sanri.tools.modules.core.security.entitys.UserProfile;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.ChatContact;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.Message;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.ChatGroupRepository;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.MessageRepository;
import com.sanri.tools.modules.mock.l7.websocket.chat.repository.ChatUserRepository;
import com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.ChatSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class ChatService {

    @Autowired
    private ChatUserRepository chatUserRepository;

    @Autowired
    private MessageRepository messageRepository;

    @Autowired(required = false)
    private UserService userService;

    @Autowired
    private ChatSupport chatSupport;

    @Autowired(required = false)
    private UserOpenService userOpenService;

    @Autowired
    private ChatGroupRepository chatGroupRepository;

    /**
     * 联系人列表
     * @return
     * @throws IOException
     */
    public List<ChatContact> contacts() throws IOException {
        List<ChatContact> chatContacts = new ArrayList<>();

        String username = userService.username();
        String[] listContacts = chatUserRepository.listContacts(username);
        if (ArrayUtils.isNotEmpty(listContacts)) {
            for (String contact : listContacts) {

                UserProfile userProfile = userOpenService.profile(contact);
                Message message = messageRepository.loadLastMessage(username, contact, false);
                ChatContact chatContact = new ChatContact(userProfile);
                chatContacts.add(chatContact);
                if (message != null) {
                    chatContact.setLastContent(message.getContent());
                    chatContact.setLastSendTime(message.getSendTime());
                }
            }
        }

        // 添加聊天组
        List<String> groups = chatUserRepository.groups(username);
        if (CollectionUtils.isNotEmpty(groups)){
            for (String groupName : groups) {
                UserProfile profile = chatGroupRepository.profile(groupName);
                ChatContact chatContact = new ChatContact(profile);
                chatContact.setIndex("群组");
                chatContact.setGroup(true);
                chatContacts.add(chatContact);

                Message message = messageRepository.loadLastMessage(username, groupName, true);
                if (message != null) {
                    chatContact.setLastContent(message.getContent());
                    chatContact.setLastSendTime(message.getSendTime());
                }
            }
        }

        return chatContacts;
    }

    /**
     * 添加联系人
     * @param contact
     * @throws IOException
     */
    public void addContact(String contact) throws IOException {
        chatUserRepository.addContact(userService.username(), contact);
    }

    /**
     * 当前用户所在组织
     * @return
     */
    public List<String> userGroups(){
        String username = userService.username();
        List<String> groups = chatUserRepository.groups(username);
        return groups;
    }

    /**
     * 当前用户加入组
     * @param group
     * @throws IOException
     */
    public void joinGroup(String group) throws IOException {
        // 检查组是否存在
        boolean existGroup = chatGroupRepository.existGroup(group);
        if (!existGroup){
            throw new ToolException("不存在组 "+ group);
        }
        String username = userService.username();
        chatUserRepository.joinGroup(username, group);
    }

    /**
     * 当前用户离开组
     * @param group
     */
    public void leaveGroup(String group) throws IOException {
        String username = userService.username();
        List<String> admins = chatGroupRepository.getAdmins(group);
        if (username.equals(admins.get(0))){
            throw new ToolException("超级管理员不能离开组, 请先转让群, 如果这个群只有你一个人, 使用解散群功能");
        }
        chatUserRepository.leaveGroup(username, group);
    }

    /**
     * 聊天消息列表
     * @param contact
     * @param group
     * @return
     */
    public List<Message> messages(String contact, PageParam pageParam, boolean group) throws IOException {
        String username = userService.username();
        List<Message> messages = messageRepository.loadMessage(username, contact, null, pageParam, group);
        return messages;
    }

    /**
     * 查询历史消息
     * @param contact
     * @param pageParam
     * @param group
     * @param date
     * @return
     */
    public List<Message> historyMessages(String contact, PageParam pageParam, boolean group, String date){
        String username = userService.username();
        List<Message> messages = messageRepository.loadMessage(username, contact, date, pageParam, group);
        return messages;
    }

    public void openChat() throws IOException {
        String username = userService.username();
        chatUserRepository.openChat(username);
    }

    public void sendMessage(Message message) throws IOException {
        message.setFromContactId(userService.username());
        chatSupport.sendMessage(message);
    }

    public Set<String> messageListDates(String contact, boolean group) {
        String username = userService.username();
        Set<String> dates = messageRepository.dates(username, contact, group);
        return dates;
    }
}
